package com.finger.forest;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.custom.MyDialog;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.FzFireModel;
import com.finger.forest.utils.ClickUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 报警核查
 */
public class AlarmCheckActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "AlarmCheckActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 历史轨迹
     */
    @BindView(R.id.btn_operate)
    Button operateBtn;

    private MapView mMapView;

    //经度
    private String longitude;

    //纬度
    private String latitude;

    //报警ID（界面传值）
    private String hId;

    private MyDialog myDialog;

    private LocationDisplay mLocationDisplay;

    LinearLayout layoutHotContent;

    FzFireModel alarmDetail;

    private int type = 0;//反馈标识 0：未反馈；1：已反馈。

    @Override
    protected int setView() {
        return R.layout.activity_alarm_check;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        //接收热点经纬度
        Intent intent=getIntent();
        type = intent.getIntExtra("type",0);
        hId = intent.getStringExtra("id");
        Log.i(TAG,"id="+ hId);

        mMapView = findViewById(R.id.mapView);

        //获取报警详情
        getAlarmDetailById();
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, Double.parseDouble(latitude), Double.parseDouble(longitude), SystemConfig.mapLevel);
            mMapView.setMap(map);
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(AlarmCheckActivity.this, mMapView) {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i(TAG,e.getX()+","+e.getY());
                Log.i(TAG,"点击");
                //获取屏幕点击坐标
                android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 5);
                //this.mMapView.identifyLayerAsync(mMapView.getMap().getOperationalLayers(),mapPoint,12, false, 5);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    Envelope tEnvelope = geoElement.getGeometry().getExtent();
                                    Point tPoint = tEnvelope.getCenter();
                                    Log.e(TAG,"当前点击的："+tPoint);

                                    layoutHotContent = (LinearLayout) LayoutInflater.from(AlarmCheckActivity.this).inflate(R.layout.dialog_content_alarm, null);

                                    //设置弹框值
                                    setLayoutContent();

                                    //弹框
                                    myDialog=new MyDialog(AlarmCheckActivity.this,R.style.MyDialog);
                                    myDialog.setTitle("报警信息");
                                    myDialog.setLayout(layoutHotContent);
                                    if (type == 0){
                                        myDialog.setYesOnclickListener("核查", new MyDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesOnclick() {
                                                Intent intent = new Intent(AlarmCheckActivity.this, AlarmCheckFeedbackActivity.class);
                                                intent.putExtra("hId", hId);//报警ID
                                                startActivity(intent);
                                                finish();
                                            }
                                        });
                                    } else {
                                        myDialog.setYesOnclickListener("已核查", new MyDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesOnclick() {
                                                myDialog.dismiss();
                                            }
                                        });
                                    }
                                    myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            myDialog.dismiss();
                                        }
                                    });
                                    myDialog.show();


                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }
        });
    }

    private void setLayoutContent(){
        TextView alarmLongtitudeTv = layoutHotContent.findViewById(R.id.alarm_longtitude);//经度
        TextView alarmLatitudeTv = layoutHotContent.findViewById(R.id.alarm_latitude);//纬度
        TextView alarmUserTv = layoutHotContent.findViewById(R.id.alarm_user);//报警人
        TextView alarmPhoneTv = layoutHotContent.findViewById(R.id.alarm_phone);//报警人电话
        TextView alarmTimeTv = layoutHotContent.findViewById(R.id.alarm_time);//报警时间
        TextView alarmOutTv = layoutHotContent.findViewById(R.id.alarm_is_out);//是否扑灭
        TextView alarmReasonTv = layoutHotContent.findViewById(R.id.alarm_reason);//火灾原因
        TextView alarmPositionTv = layoutHotContent.findViewById(R.id.alarm_position);//位置

        alarmLongtitudeTv.setText(alarmDetail.getFiLongitude().toString());
        alarmLatitudeTv.setText(alarmDetail.getFiLatitude().toString());
        alarmUserTv.setText(alarmDetail.getFiReporter());
        alarmPhoneTv.setText(alarmDetail.getFiPhoneNumber());
        alarmTimeTv.setText(alarmDetail.getFiReportTime());
        alarmOutTv.setText(alarmDetail.getFiIsQuench());
        alarmReasonTv.setText(alarmDetail.getFiFireCause()==null?"未知":alarmDetail.getFiFireCause().toString());
        alarmPositionTv.setText(alarmDetail.getFiPosition()==null?"未知":alarmDetail.getFiPosition());
    }

    //获取报警详情
    private void getAlarmDetailById() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("id",hId);
        presenter.queryAlarmDetail(maps);//查询报警详情
    }

    //创建要素集合
    FeatureCollection featureCollection = new FeatureCollection();
    //创建要素集合图层
    FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

    //添加报警和巡护员位置
    private void createFeatureCollection() {
        //将图层添加到地图
        mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
        createPointTable(featureCollection);
    }

    /**
     * 添加报警图标
     */
    private void createPointGraphics() {
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        Point point2 = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_alarm);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        Graphic pointGraphic2 = new Graphic(point2, pms);
        mGraphicsOverlay.getGraphics().add(pointGraphic2);

        //定位热点位置
        //mMapView.setViewpointCenterAsync(point2);
    }

    private void createPointTable(FeatureCollection featureCollection) {

        List<Field> pointFields = new ArrayList<>();
        pointFields.add(Field.createString("Place", "Place Name", 50));

        //------ 文字 start--------
        //要素集合table
        FeatureCollectionTable pointsTableT = new FeatureCollectionTable(pointFields, GeometryType.POINT, SpatialReferences.getWgs84());
        //TextSymbol textSymbol = new TextSymbol(10, hAlarmName, Color.WHITE, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.TOP);
        TextSymbol textSymbol = new TextSymbol(10, "", Color.WHITE, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.TOP);
        textSymbol.setOffsetY(-10);
        textSymbol.setFontFamily("DroidSansFallback.ttf");
        SimpleRenderer renderer = new SimpleRenderer(textSymbol);
        pointsTableT.setRenderer(renderer);

        // Malibu Pier
        Map<String, Object> attributesT = new HashMap<>();
        attributesT.put(pointFields.get(0).getName(), "Malibu Pier");
        Point pointT = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());

        List<Feature> featuresT = new ArrayList<>();
        featuresT.add(pointsTableT.createFeature(attributesT, pointT));

        pointsTableT.addFeaturesAsync(featuresT);

        //热点
        featureCollection.getTables().add(pointsTableT);
        //------ 文字 end--------
    }

    @OnClick({R.id.btn_back, R.id.btn_operate })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //开始出发、开始反馈
                case R.id.btn_operate:
                    if (operateBtn.getText().equals("开始出发")) {
                        operateBtn.setText("开始反馈");
                        //路线导航
                        //..
                    } else if (operateBtn.getText().equals("开始反馈")) {
                        Intent intent = new Intent(AlarmCheckActivity.this, AlarmCheckFeedbackActivity.class);
                        intent.putExtra("hId", hId);//报警ID
//                        intent.putExtra("hAlarmNo", hAlarmNo);//报警编号
                        startActivity(intent);
                        finish();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    private void setupLocationDisplay() {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();
        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "位置信息："+ point.toString());
                //获取到位置信息后，移除监听
                mLocationDisplay.removeLocationChangedListener(this);
                //获取到位置信息后，定位巡查员位置
                //createPointTablePeople(featureCollection, point.getX(), point.getY());
            }
        });
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //报警详情
            case ResponseTag.QUERY_ALARM_DETAIL:
                alarmDetail = (FzFireModel) model;
                longitude = alarmDetail.getFiLongitude().toString();
                latitude = alarmDetail.getFiLatitude().toString();

                //初始化地图
                setupMap();

                //添加报警和巡护员位置
                createFeatureCollection();

                //添加报警图标
                createPointGraphics();
                break;

            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }
}
